package com.xiaolv.web.config;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

/**
 * 月范围分片
 *
 * @author lvlinguang
 * @date 2020-08-10 19:09
 */
public class MonthRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {

    /**
     * 设置分片
     *
     * @param collection
     * @param rangeShardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
        Collection<String> result = new LinkedHashSet<>();
        DateFormat sdf = new SimpleDateFormat("yyyyMM");
        //日期
        Range<String> ranges = rangeShardingValue.getValueRange();
        Date startTime = dateFormat(ranges.lowerEndpoint());
        Date endTime = dateFormat(ranges.upperEndpoint());

        Calendar cal = Calendar.getInstance();
        while (startTime.getTime() <= endTime.getTime()) {
            String value = sdf.format(startTime);
            for (String each : collection) {
                if (each.endsWith(value)) {
                    result.add(each);
                    break;
                }
            }
            cal.setTime(startTime);
            cal.add(Calendar.MONTH, 1);
            startTime = cal.getTime();
        }
        if (result.size() == 0) {
            result = collection;
        }
        return result;
    }

    /**
     * 日期转换
     *
     * @param date
     * @return
     */
    public Date dateFormat(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }
}
